package com.hehan.hhdemo.service.impl;

import com.hehan.hhdemo.po.EsConfigEntity;
import com.hehan.hhdemo.service.IJestElasticsearchManageRepository;
import com.hehan.hhdemo.util.JsonUtils;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by hehan on 2018/11/7.
 */
@Repository
public class JestElasticsearchManageRepositoryImpl <T> implements IJestElasticsearchManageRepository {
    private static final Logger LOGGER = LoggerFactory.getLogger(JestElasticsearchManageRepositoryImpl.class);

    private static final String ES_INSERT_ID = "id";//所取对象的字段名称，取该值用作ES的唯一ID

   @Autowired
   private JestClient jestClient;

    /**
     * 根据ID泛型删除
     *
     * @param
     * @return
     */
    @Override
    public String deleteEntityByIdToEs( EsConfigEntity es) {
        Delete delete = new Delete.Builder(es.getHandleStr()).index(es.getEsIndex()).type(es.getEsType()).build();
        JestResult jr = null;
        try {

            jr = jestClient.execute(delete);
        } catch (IOException e) {
            LOGGER.error("deleteEntityByIdToEs", e);
            e.printStackTrace();
        }
        return jr.getJsonString();
    }

    @Override
    public String addEntityByIdToEs(EsConfigEntity es, Object obj) {
        DocumentResult result = null;
        Field[] fs = obj.getClass().getDeclaredFields();
        String insertEsId = null;
        for (Field field : fs) {
            field.setAccessible(true);
            if (field.getName().equals(ES_INSERT_ID)) {
                try {
                    insertEsId = field.get(obj).toString();
                    break;
                } catch (IllegalAccessException e) {
                    LOGGER.error("addEntityByIdToEs", e);
                    e.printStackTrace();
                }
            }
        }
        try {
            result = jestClient.execute(new Index.Builder(obj)
                    .id(insertEsId)
                    .index(es.getEsIndex())
                    .type(es.getEsType())
                    .refresh(true)
                    .build());
        } catch (IOException e) {
            LOGGER.error("addEntityByIdToEs", e);
            e.printStackTrace();
        }
        return result.getJsonString();
    }




    @Override
    public String addListToEs(EsConfigEntity es, Class entity, List tList) {
        Bulk.Builder bulk = new Bulk.Builder().defaultIndex(es.getEsIndex()).defaultType(es.getEsType());
        for (Object obj : tList) {
            T t = (T) obj;
            Field[] fs = t.getClass().getDeclaredFields();
            String insertEsId = null;
            for (Field field : fs) {
                field.setAccessible(true);
                if (field.getName().equals(ES_INSERT_ID)) {
                    try {
                        insertEsId = field.get(t).toString();
                        break;
                    } catch (IllegalAccessException e) {
                        LOGGER.error("addListToEs", e);
                        e.printStackTrace();
                    }
                }
            }
            Index index = new Index.Builder(obj).id(insertEsId).build();
            bulk.addAction(index);
        }
        BulkResult br = null;
        try {
            br = jestClient.execute(bulk.build());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return br.getJsonString();
    }

    @Override
    public String updateEntityToEs( EsConfigEntity es, Object obj) {
        String sourceJson = JsonUtils.obj2Json(obj, false);
        String script = "{\"doc\" : " + sourceJson + "}";
        Field[] fs = obj.getClass().getDeclaredFields();
        String insertEsId = null;
        for (Field field : fs) {
            field.setAccessible(true);
            if (field.getName().equals(ES_INSERT_ID)) {
                try {
                    insertEsId = field.get(obj).toString();
                    break;
                } catch (IllegalAccessException e) {
                    LOGGER.error("updateEntityToEs", e);
                    e.printStackTrace();
                }
            }
        }
        Update update = new Update.Builder(script).index(es.getEsIndex()).type(es.getEsType()).id(insertEsId).build();
        JestResult result = null;
        try {
            result = jestClient.execute(update);
        } catch (IOException e) {
            LOGGER.error("updateEntityToEs", e);
            e.printStackTrace();
        }
        return result.getJsonString();
    }
}

